package artid.com.arttogo.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import artid.com.arttogo.R;
import artid.com.arttogo.bean.CelebritySealParser;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.network.VolleyBasic;
import artid.com.arttogo.network.VolleyCallback;
import artid.com.arttogo.network.VolleyData;
import artid.com.arttogo.network.VolleyMap;
import artid.com.arttogo.utils.ToastUtil;
import artid.com.arttogo.view.alphabeticalindex.IndexesMechanismBean;
import artid.com.arttogo.view.alphabeticalindex.IndexesMechanism_Adapter;
import artid.com.arttogo.view.alphabeticalindex.MyLetterAlistView;
import artid.com.arttogo.view.alphabeticalindex.PinyinComparator_Mechanism;

/**
 * 名人印章页面
 */

public class CelebritySeal_Activity extends BaseActivity implements View.OnClickListener {
    private Context mContext;
    private RelativeLayout searchRL;
    private EditText searchbox_Ed;
    private TextView searchbox_hint,searchbox_CancelBtn,celebritySealNum;
    private ImageView searchBtn,searchbox_icon;
    private String keyword="";//搜索关键字
    private ListView mListView;
    private LinearLayout noDataLL;
    private TextView noDataHintTv;
    // 右侧A-Z字母列表
    private MyLetterAlistView letterListView;
    // dialog text
    private TextView overlay;
    // 估计是弹出dialog线程
    private OverlayThread overlayThread;
    //机构Adapter
    private IndexesMechanism_Adapter adapter;
    private Handler handler;
    /**
     * 汉字转换成拼音的类
     */
    private List<IndexesMechanismBean> dateList;
    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator_Mechanism pinyinComparator;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_celebrityseal);
        initView();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    private void initView() {
        mContext = CelebritySeal_Activity.this;
        mBack = (ImageView) findViewById(R.id.back_btn);
        mBack.setOnClickListener(this);
        mTittle = (TextView) findViewById(R.id.tittle_text);
        mTittle.setText("名人印谱");
        searchBtn= (ImageView) findViewById(R.id.CelebritySeal_title_searchBtn);
        searchBtn.setOnClickListener(this);
        handler = new Handler();
        overlayThread = new OverlayThread();
        celebritySealNum= (TextView) findViewById(R.id.CelebritySeal_num);
        mListView = (ListView) findViewById(R.id.CelebritySeal_ListView);
        mListView.setOnItemClickListener(onItemClick);
        letterListView = (MyLetterAlistView) findViewById(R.id.CelebritySeal_MyLetterAlistView);
        letterListView.setVisibility(View.GONE);
        noDataLL = (LinearLayout) findViewById(R.id.ll_hint);
        noDataHintTv= (TextView) findViewById(R.id.ll_hint_tv);
        //搜索框初始化组件
        searchRL= (RelativeLayout) findViewById(R.id.CelebritySeal_searchRL);
        searchbox_Ed=(EditText) findViewById(R.id.CelebritySeal_searchbox_EditText);
        searchbox_Ed.setOnFocusChangeListener(onFocusChange);
        searchbox_Ed.setOnEditorActionListener(OnEditorAction);
        searchbox_hint=(TextView) findViewById(R.id.CelebritySeal_searchbox_hint);
        searchbox_icon=(ImageView) findViewById(R.id.CelebritySeal_searchbox_icon);
        searchbox_CancelBtn=(TextView) findViewById(R.id.CelebritySeal_searchbox_CancelBtn);
        searchbox_CancelBtn.setOnClickListener(this);
        getData("");
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.CelebritySeal_title_searchBtn:
                searchRL.setVisibility(View.VISIBLE);
                showSoftInputFromWindow(CelebritySeal_Activity.this,searchbox_Ed);
                break;
            case R.id.CelebritySeal_searchbox_CancelBtn:
                //搜索取消键
                searchbox_Ed.setText("");
                searchRL.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    TextView.OnEditorActionListener OnEditorAction=new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId,
                                      KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                keyword=searchbox_Ed.getText().toString();
                getData(keyword);
                return true;
            }
            return false;
        }
    };

    /**
     * 搜索框焦点监听
     */
    View.OnFocusChangeListener onFocusChange=new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            // TODO Auto-generated method stub
            if(hasFocus){
                //获得焦点
                searchbox_hint.setVisibility(View.GONE);
                searchbox_icon.setVisibility(View.VISIBLE);
                searchbox_CancelBtn.setVisibility(View.VISIBLE);
            }else{
                //失去焦点
                searchbox_hint.setVisibility(View.VISIBLE);
                searchbox_icon.setVisibility(View.GONE);
                searchbox_CancelBtn.setVisibility(View.GONE);
                hideSoftInput(CelebritySeal_Activity.this);
            }
        }
    };

    /**
     * EditText获取焦点并显示软键盘
     */
    public static void showSoftInputFromWindow(Activity activity, EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    /**
     * 关闭软键盘
     * @param mContext
     */
    /**
     * 隐藏软键盘
     */
    @SuppressWarnings("static-access")
    public static void hideSoftInput(Activity activity){
        /**隐藏软键盘**/
        View view = activity.getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputmanger = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 为ListView填充数据
     *
     * @param date
     * @return
     */
    @SuppressLint("DefaultLocale")
    private List<IndexesMechanismBean> filledData(List<IndexesMechanismBean> date) {
        List<IndexesMechanismBean> mList = new ArrayList<IndexesMechanismBean>();
        for (int i = 0; i < date.size(); i++) {
            IndexesMechanismBean mBean = new IndexesMechanismBean();
            mBean.setName(date.get(i).getName());
            mBean.setId(date.get(i).getId());
            // 汉字转换成拼音
            String pinyin = getFirstSpell(date.get(i).getName());
            try {
                String sortString = pinyin.substring(0, 1).toUpperCase(Locale.CHINESE);
                // 正则表达式，判断首字母是否是英文字母
                if (sortString.matches("[A-Z]")) {
                    mBean.setSortLetters(sortString.toUpperCase());
                } else {
                    mBean.setSortLetters("#");
                }
            } catch (Exception e) {
                // TODO: handle exception
                //当遇到非法字符的时候会出现报错的问题，所以直接将他设置为#状态
                mBean.setSortLetters("#");
            }

            mList.add(mBean);
        }
        return mList;

    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("CelebritySeal_ Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }

    // 右侧A-Z字母监听
    private class LetterListViewListener implements MyLetterAlistView.OnTouchingLetterChangedListener {

        @Override
        public void onTouchingLetterChanged(final String s) {
            // 该字母首次出现的位置
            int position = adapter.getPositionForSection(s.charAt(0));
            if (position != -1) {
                mListView.setSelection(position);
                overlay.setText(dateList.get(position).getSortLetters());
                overlay.setVisibility(View.VISIBLE);
                handler.removeCallbacks(overlayThread);
                // 延迟一秒后执行，让overlay为不可见
                handler.postDelayed(overlayThread, 500);
            }
        }
    }

    // 初始化汉语拼音首字母弹出提示框
    private void initOverlay() {
        LayoutInflater inflater = LayoutInflater.from(CelebritySeal_Activity.this);
        overlay = (TextView) inflater.inflate(R.layout.view_overlay, null);
        overlay.setVisibility(View.INVISIBLE);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                PixelFormat.TRANSLUCENT);
        WindowManager windowManager = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        windowManager.addView(overlay, lp);
    }

    // 设置overlay不可见
    private class OverlayThread implements Runnable {

        @Override
        public void run() {
            overlay.setVisibility(View.GONE);
        }

    }

    /**
     * 汉字转换为汉语拼音首字母
     *
     * @return 拼音
     */
    public static String getFirstSpell(String chinese) {
        StringBuffer pybf = new StringBuffer();
        char[] arr = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (char curchar : arr) {
            if (curchar > 128) {
                try {
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(curchar, defaultFormat);
                    if (temp != null) {
                        pybf.append(temp[0].charAt(0));
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pybf.append(curchar);
            }
        }
        return pybf.toString().replaceAll("\\W", "").trim();
    }

    /**
     * item点击事件
     */
    AdapterView.OnItemClickListener onItemClick = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Intent intent=new Intent(mContext,CelebritySealInfo_Activity.class);
            intent.putExtra("CelebritySealID",dateList.get(i).getId());
            intent.putExtra("CelebritySealName",dateList.get(i).getName());
            startActivity(intent);
        }
    };


    /**
     * 获取数据
     * key为搜索使用
     */
    private void getData(final String key) {
        VolleyBasic.getInstance(this).post(Cache.celebrityartistList,
                VolleyMap.getInstance().celebrityartistList(key),
                CelebritySealParser.class, new VolleyCallback() {

                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        List<CelebritySealParser> list = (List<CelebritySealParser>) vd.getList();
                        celebritySealNum.setText(list.size()+"人");
                        Log.d("log", "list:" + list.toString());
                        dateList=new ArrayList<IndexesMechanismBean>();
                        if (list != null && list.size() != 0) {
                            noDataLL.setVisibility(View.GONE);
                            for (int i = 0; i < list.size(); i++) {
                                IndexesMechanismBean bean1 = new IndexesMechanismBean();
                                bean1.setId(list.get(i).getId());
                                bean1.setName(list.get(i).getSeller_name());
                                dateList.add(bean1);
                            }
                            dateList = filledData(dateList);
                            Log.d("log", "dateList:" + dateList.toString());
                            /** 给ListView设置adapter **/
                            // 根据拼音排序
                            pinyinComparator = new PinyinComparator_Mechanism();
                            Collections.sort(dateList, pinyinComparator);// 根据a-z进行排序源数据

                            if (dateList != null && dateList.size() != 0) {
                                List<String> letterAlistView_list = new ArrayList<String>();
                                for (int i = 0; i < dateList.size(); i++) {
                                    //先将数据添加到集合
                                    letterAlistView_list.add(dateList.get(i).getSortLetters().toString());
                                }
                                //去重
                                for (int i = 0; i < letterAlistView_list.size() - 1; i++) {
                                    for (int j = letterAlistView_list.size() - 1; j > i; j--) {
                                        if (letterAlistView_list.get(j).equals(letterAlistView_list.get(i))) {
                                            letterAlistView_list.remove(j);
                                        }
                                    }
                                }
                                String[] letterAlistView_Data = new String[letterAlistView_list.size()];
                                for (int i = 0; i < letterAlistView_list.size(); i++) {
                                    letterAlistView_Data[i] = letterAlistView_list.get(i).toString();
                                }
                                letterListView.setData(letterAlistView_Data);
                                letterListView.setVisibility(View.VISIBLE);
                            }

                            adapter = new IndexesMechanism_Adapter(mContext, dateList);
                            mListView.setAdapter(adapter);
                            mListView.setOnItemClickListener(onItemClick);
                            initOverlay();
                            letterListView.setOnTouchingLetterChangedListener(new LetterListViewListener());
                        }else{
                            if(TextUtils.isEmpty(searchbox_Ed.getText().toString())) {
                                noDataHintTv.setText("目前还没有相关内容");
                                noDataLL.setVisibility(View.VISIBLE);
                            }else{
                                celebritySealNum.setText(0+"人");
                                dateList=new ArrayList<IndexesMechanismBean>();
                                adapter = new IndexesMechanism_Adapter(mContext, dateList);
                                mListView.setAdapter(adapter);
                                letterListView.setVisibility(View.GONE);
                                noDataHintTv.setText("暂未找到您搜索的相关内容");
                                noDataLL.setVisibility(View.VISIBLE);
                            }
                        }
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub
                        if(TextUtils.isEmpty(searchbox_Ed.getText().toString())) {
                            noDataHintTv.setText("目前还没有相关内容");
                            noDataLL.setVisibility(View.VISIBLE);
                        }else{
                            celebritySealNum.setText(0+"人");
                            dateList=new ArrayList<IndexesMechanismBean>();
                            adapter = new IndexesMechanism_Adapter(mContext, dateList);
                            mListView.setAdapter(adapter);
                            letterListView.setVisibility(View.GONE);
                            noDataHintTv.setText("暂未找到搜索的相关内容");
                            noDataLL.setVisibility(View.VISIBLE);
                        }
                    }
                });
    }
}
